#include<stdio.h>
#include<stdlib.h>
#include<string.h> 
#include"users.h"
#include "part1.h"
#include"stdlib.h"
// 根据用户名查找用户并打印信息（返回首个匹配节点）
struct users* findUserByUsername(struct users* head, const char* username) {
    struct users* current = head;
    while (current != NULL) {
        if (strcmp(current->username, username) == 0&& current->type == 3) {
            // 转换用户类型为可读字符串
            const char* typeStr = "未知类型";
            switch(current->type) {
                case 1: typeStr = "管理员"; break;
                case 2: typeStr = "员工";   break;
                case 3: typeStr = "用户";   break;
            }
            // 打印用户详细信息
            printf("\n=== 找到用户 ===\n");
            printf("用户名：%s\n", current->username);
            printf("密码：%s\n", current->password);
            printf("类型：%s\n", typeStr);
            printf("电话号码：%s\n", current->phonenumber);
            printf("会员等级：%d\n", current->members.level);
            printf("会员积分：%d\n\n", current->members.points);
            return current;
        }
        current = current->next;
    }
   printf("未找到用户名为 [%s] 的用户\n", username);
    freeUsers(head);
    return NULL;
}

// 根据电话号码查找用户并打印信息（返回首个匹配节点）
struct users* findUserByPhoneNumber(struct users* head, const char* phonenumber) {
    struct users* current = head;
    while (current != NULL) {
        if (strcmp(current->phonenumber, phonenumber) == 0&& current->type == 3) {
            // 转换用户类型为可读字符串
            const char* typeStr = "未知类型";
            switch(current->type) {
                case 1: typeStr = "管理员"; break;
                case 2: typeStr = "员工";   break;
                case 3: typeStr = "用户";   break;
            }
            
            // 打印用户详细信息
            printf("\n=== 找到用户 ===\n");
            printf("用户名：%s\n", current->username);
            printf("密码：%s\n", current->password);
            printf("类型：%s\n", typeStr);
            printf("电话号码：%s\n", current->phonenumber);
            printf("会员等级：%d\n", current->members.level);
            printf("会员积分：%d\n\n", current->members.points);
            return current;
        }
        current = current->next;
    }
    printf("未找到电话号码为 [%s] 的用户\n", phonenumber);
    freeUsers(head);
    return NULL;
}
int addUserToFile_1(char *a,char*b,char*c) {
    Users newUser;
    
    // 读取用户输入
    // printf("请输入用户名（最大19字符）：");
    // scanf("%19s", newUser.username);
    
    // printf("请输入密码（最大19字符）：");
    // scanf("%19s", newUser.password);

     newUser.type=1;
    
    // printf("请输入电话号码（最大19字符）：");
    // scanf("%19s", newUser.phonenumber);
    strcpy(newUser.username,a);
    strcpy(newUser.password,b);
    strcpy(newUser.phonenumber,c);
    newUser.members.level=0;
    
    newUser.members.points=0;
    
    // 打开文件追加写入
    FILE* file = fopen("users.txt", "a");
    if (file == NULL) {
        printf("无法打开文件！\n");
        return 0;
    }
    
    // 按格式写入文件，保持与原始格式一致
    fprintf(file, "%s  %s  %d  %s  %d  %d\n",
            newUser.username,
            newUser.password,
            newUser.type,
            newUser.phonenumber,
            newUser.members.level,
            newUser.members.points);
    
    fclose(file);
    printf("用户信息已成功保存！\n");
    return 1;
}

int addUserToFile_2(char*a,char*b,char*c) {
    Users newUser;
    
    // 读取用户输入
    // printf("请输入用户名（最大19字符）：");
    // scanf("%19s", newUser.username);
    
    // printf("请输入密码（最大19字符）：");
    // scanf("%19s", newUser.password);
    
     newUser.type=2;
    
    // printf("请输入电话号码（最大19字符）：");
    // scanf("%19s", newUser.phonenumber);
    
    newUser.members.level=0;
    
    newUser.members.points=0;
     strcpy(newUser.username,a);
     strcpy(newUser.password,b);
     strcpy(newUser.phonenumber,c);
    // 打开文件追加写入
    FILE* file = fopen("users.txt", "a");
    if (file == NULL) {
        printf("无法打开文件！\n");
        return 0;
    }
    
    // 按格式写入文件，保持与原始格式一致
    fprintf(file, "%s  %s  %d  %s  %d  %d\n",
            newUser.username,
            newUser.password,
            newUser.type,
            newUser.phonenumber,
            newUser.members.level,
            newUser.members.points);
    
    fclose(file);
    printf("用户信息已成功保存！\n");
    return 1;
}

int addUserToFile_3(char*a,char*b,char*c ,int d,int e) {
    Users newUser;
    
    // 读取用户输入
    // printf("请输入用户名（最大19字符）：");
    // scanf("%19s", newUser.username);
    
    // printf("请输入密码（最大19字符）：");
    // scanf("%19s", newUser.password);
    
     newUser.type=3;
    
    // printf("请输入电话号码（最大19字符）：");
    // scanf("%19s", newUser.phonenumber);
    
    // printf("请输入会员等级（0-4）：");
    // scanf("%d", &newUser.members.level);
    
    // printf("请输入会员积分：");
    // scanf("%d", &newUser.members.points);
    
    // 打开文件追加写入
     newUser.members.level=d;
     newUser.members.points=e;
    FILE* file = fopen("users.txt", "a");
    if (file == NULL) {
        printf("无法打开文件！\n");
        return 0;
    }
    strcpy(newUser.username,a);
    strcpy(newUser.password,b);
    strcpy(newUser.phonenumber,c);
    // 按格式写入文件，保持与原始格式一致
    fprintf(file, "%s  %s  %d  %s  %d  %d\n",
            newUser.username,
            newUser.password,
            newUser.type,
            newUser.phonenumber,
            newUser.members.level,
            newUser.members.points);
    
    fclose(file);
    printf("用户信息已成功保存！\n");
    return 1;
}

//从文件删除用户
/*void deleteUserFromFile() {
    // 加载用户链表
    Users *head = loadUsersFromFile("users.txt");
    if (!head) {
        printf("无法加载用户数据！\n");
        return;
    }

    // 获取要删除的用户名
    char target[20];
    printf("请输入要删除的用户名：");
    scanf("%19s", target);

    // 遍历链表查找用户
    Users *curr = head;
    Users *prev = NULL;
    int found = 0;
    
    while (curr) {
         
        if (strcmp(curr->username, target) == 0) { 
            // 删除节点操作
            if (prev) {
                prev->next = curr->next;
            } else {
                head = curr->next;  // 处理头节点
            }
            free(curr);
            found = 1;
            break;
        }
        prev = curr;
        curr = curr->next;
    }

    if (!found) {
        printf("用户 %s 不存在！\n", target);
        // 释放整个链表内存
        while (head) {
            Users *temp = head;
            head = head->next;
            free(temp);
        }
        return;
    }

    // 将更新后的链表写入文件
    FILE *file = fopen("users.txt", "w");
    if (!file) {
        printf("无法打开文件！\n");
        // 释放剩余链表内存
        while (head) {
            Users *temp = head;
            head = head->next;
            free(temp);
        }
        return;
    }

    // 遍历链表写入文件
    curr = head;
    while (curr) {
        fprintf(file, "%s  %s  %d  %s  %d  %d\n",
                curr->username,
                curr->password,
                curr->type,
                curr->phonenumber,
                curr->members.level,
                curr->members.points);
        curr = curr->next;
    }

    fclose(file);

     
    while (head) {
        Users *temp = head;
        head = head->next;
        free(temp);
    }

    printf("用户 %s 已成功删除！\n", target);
}*/
/**
 * @brief 从链表删除用户（纯C语言核心）
 * @param head 用户链表头指针（传入二级指针以便修改头节点）
 * @param target_username 要删除的用户名
 * @return 删除成功返回1，失败返回0
 */
int deleteUser(Users** head, const char* target_username)
{
    if (!head || !*head || !target_username) return 0;

    Users* curr = *head;
    Users* prev = NULL;
    int found = 0;

    while (curr) {
        if (strcmp(curr->username, target_username) == 0) {
            // 执行删除操作
            if (prev) {
                prev->next = curr->next;
            } else {
                *head = curr->next; // 修改头指针
            }
            free(curr);
            found = 1;
            break;
        }
        prev = curr;
        curr = curr->next;
    }
    return found;
}
int saveListToFile(Users* head, const char* filename)
{
    FILE* file = fopen(filename, "w");
    if (!file) return 0;

    Users* curr = head;
    while (curr) {
        fprintf(file, "%s %s %d %s %d %d\n",
                curr->username,
                curr->password,
                curr->type,
                curr->phonenumber,
                curr->members.level,
                curr->members.points);
        curr = curr->next;
    }
    fclose(file);
    return 1;
}
//根据用户名查找用户并修改会员信息
/*struct users* modifyUserMembers(Users* head, const char* username) {
    Users* current = head;
    int found = 0;

    while (current) {
        if (strcmp(current->username, username) == 0 && current->type == 3) {
            found = 1;
            // 打印用户详细信息
            printf("\n=== 用户详细信息 ===\n");
            printf("1. 用户名：%s\n", current->username);
            printf("2. 密码：%s\n", current->password);
            printf("3. 类型：%d\n", current->type);
            printf("4. 电话号码：%s\n", current->phonenumber);
            printf("5. 会员等级：%d\n", current->members.level);
            printf("6. 会员积分：%d\n", current->members.points);
            // 输入验证循环
            int choice;
            do {
                printf("\n请输入要修改的项 (1-6, 0取消): ");
                scanf("%d", &choice);
                if (choice == 0) {
                    printf("修改已取消\n");
                    return 0;
                }
            } while (choice < 1 || choice > 6);

            // 清空输入缓冲区
            int c;
            while ((c = getchar()) != '\n' && c != EOF);

            switch (choice) {
                case 1: {
                    char newName[20];
                    printf("请输入新的用户名(最大19字符): ");
                    fgets(newName, sizeof(newName), stdin);
                    newName[strcspn(newName, "\n")] = '\0'; // 去除换行符
                    strncpy(current->username, newName, 19);
                    break;
                }
                case 2: {
                    char newPass[20];
                    printf("请输入新的密码(最大19字符): ");
                    fgets(newPass, sizeof(newPass), stdin);
                    newPass[strcspn(newPass, "\n")] = '\0';
                    strncpy(current->password, newPass, 19);
                    break;
                }
                case 3: {
                    int newType;
                    do {
                        printf("请输入新的类型 (1-管理员 2-员工 3-用户): ");
                        scanf("%d", &newType);
                    } while (newType < 1 || newType > 3);
                    current->type = newType;
                    break;
                }
                case 4: {
                    char newPhone[20];
                    printf("请输入新的电话号码(最大19字符): ");
                    fgets(newPhone, sizeof(newPhone), stdin);
                    newPhone[strcspn(newPhone, "\n")] = '\0';
                    strncpy(current->phonenumber, newPhone, 19);
                    break;
                }
                case 5: {
                    int newLevel;
                    do {
                        printf("请输入新的会员等级 (0-4): ");
                        scanf("%d", &newLevel);
                    } while (newLevel < 0 || newLevel > 4);
                    current->members.level = newLevel;
                    break;
                }
                case 6: {
                    int newPoints;
                    do {
                        printf("请输入新的会员积分 (≥0): ");
                        scanf("%d", &newPoints);
                    } while (newPoints < 0);
                    current->members.points = newPoints;
                    break;
                }
                
            } 
            saveUsersToFilel(head, "users.txt");//立即保存修改到文件
                printf("\n修改已保存！\n");
                return current;
        }
        current = current->next;
    }

    if (!found) {
        printf("\n错误：未找到用户 %s 或类型不是用户！\n", username);
    }

    // 释放链表内存
    Users* temp;
    while (head) {
        temp = head;
        head = head->next;
        free(temp);
    }
    return 0;
}*/

Users* modifyUsersMembers(Users* head,char* username, int choice, char* new_value_str)
{
    Users* current = head;
    int found = 0;

    while (current) {
        if (strcmp(current->username, username) == 0 && current->type == 3) {
            found = 1;

            // 输入验证
            int valid = 1;
            int numeric_value = 0;

            switch (choice) {
            case 1: // 用户名
                if (strlen(new_value_str) > 19) valid = 0;
                else strncpy(current->username, new_value_str, 19);
                break;

            case 2: // 密码
                if (strlen(new_value_str) > 19) valid = 0;
                else strncpy(current->password, new_value_str, 19);
                break;

            case 3: // 类型
                numeric_value = atoi(new_value_str);
                if (numeric_value < 1 || numeric_value > 3) valid = 0;
                else current->type = numeric_value;
                break;

            case 4: // 电话号码
                if (strlen(new_value_str) > 19) valid = 0;
                else strncpy(current->phonenumber, new_value_str, 19);
                break;

            case 5: // 会员等级
                numeric_value = atoi(new_value_str);
                if (numeric_value < 0) valid = 0;
                else current->members.level = numeric_value;
                break;

            case 6: // 会员积分
                numeric_value = atoi(new_value_str);
                if (numeric_value < 0) valid = 0;
                else current->members.points = numeric_value;
                break;

            default:
                valid = 0;
            }

            if (!valid) return NULL;

            saveUsersToFilel(head, "users.txt");
            return current;
        }
        current = current->next;
    }

    if (!found) {
        fprintf(stderr, "Error: User %s not found or invalid type\n", username);
    }
    return NULL;
}

int saveUsersToFilel(Users* head, const char* filename) {
    FILE* file = fopen(filename, "w");
    if (!file) {
        printf("无法打开文件进行写入！\n");
        return 1;  // 返回错误码
    }

    Users* current = head;
    while (current) {
        fprintf(file, "%s  %s  %d  %s  %d  %d\n",
                current->username,
                current->password,
                current->type,
                current->phonenumber,
                current->members.level,
                current->members.points);
        current = current->next;
    }
    fclose(file);
    return 0;  // 成功返回0
}

